<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed hihi');

class Horoscope extends CI_Controller {
	function __construct() {
		parent::__construct();
		$this->load->helper(array('form', 'url'));
		$this->load->library('session');
	}
	public function index()
	{
		$this->load->library('form_validation');

		$this->form_validation->set_rules('phone_number', 'số điện thoại', 'required|regex_match[/^0\(?([0-9]{2})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4,5})$/]');
		$this->form_validation->set_rules('year','ngày sinh', 'callback_dob_check');

		$this->form_validation->set_message('required', 'Bạn cần phải nhập %s để tiếp tục');

		$this->form_validation->set_message('regex_match', 'Bạn cần phải nhập %s có thật để tiếp tục');


		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('index');

		}
		else
		{
			$day = $this->input->post('day');
			$month = $this->input->post('month');
			$year = $this->input->post('year');
			$phone_number = $this->input->post('phone_number');
			$this->load->model('User_model');
			try {
				date_default_timezone_set('Asia/Ho_Chi_Minh');
				$dob = new DateTime();
				$dob->setDate($year, $month , $day);
			}
			catch (Exception $e) {
				echo $e->getMessage();
			}
			//	var_dump($dob);die();
			$uniqid = uniqid();

			$rand_start = rand(1,5);
			// 	    	{"status":status, "sms":"nội dung tin nhắn cần trả về cho khách hàng", "type":"loại tin nhắn"}

			$rand_8_char = substr($uniqid,$rand_start,8);

			$id = $this->User_model->add_new_user($dob->format("Y-m-d H:i:s"), $phone_number, $rand_8_char);
			$this->session->set_userdata('id', $id);

			// 			Dau so mobi
			// 			090
			// 			093
			// 			0120
			// 			0121
			// 			0122
			// 			0126
			// 			0128
			if (($this->startsWith($phone_number, '090'))||
					($this->startsWith($phone_number, '093'))||
					($this->startsWith($phone_number, '0120'))||
					($this->startsWith($phone_number, '0121'))||
					($this->startsWith($phone_number, '0122'))||
					($this->startsWith($phone_number, '0126'))||
					($this->startsWith($phone_number, '0128'))) {
				$this->OTPRequest($phone_number, $rand_8_char);

				redirect('horoscope/verify');
			}
			else {
				redirect('horoscope/register');
			}
		}

	}
	public function register() {
		if (!$this->session->userdata('id')) {
			redirect('horoscope/index');
		}
		else {
			$this->session->unset_userdata('id');
			$this->load->view('index');
		}
	}
	public function verify () {
		// 		$requestId = $this->input->get('req');
		if (!$this->session->userdata('id')) {
			redirect('horoscope/index');
		}
		$this->load->library('form_validation');

		$this->form_validation->set_rules('verify', 'Mã xác nhận', 'callback_check_verify');
		if ($this->form_validation->run() === FALSE)
		{
			$this->load->view('index');
		}
		else {
			redirect('horoscope/success');
		}


	}
	public function check_verify($otp) {

		$this->load->model('User_model');
		$id = $this->session->userdata('id');

		$user = $this->User_model->getUserByID($id);
		if ($user == null) {
			return false;
		}
		// 		var_dump($user);
		$requestId = $user->requestID;
		$result = $this->SUBRequest($user->phone_number, $requestId, $otp);
		// 		var_dump($result['SUBRequestResult']);
		if ($result['SUBRequestResult'] == '200') {
			$this->session->set_userdata('otp', $otp);
			$this->session->set_userdata('requestId',$requestId);
			$this->session->set_userdata('phone_number',$user->phone_number);
			return TRUE;
		}
		else {
			$this->form_validation->set_message('check_verify', '%s không chính xác');

			return FALSE;
		}
	}

	public function success () {
		if (!$this->session->userdata('id')) {
			redirect('horoscope/index');
		}
		$id = $this->session->userdata('id');
		$otp = $this->session->userdata('otp');
		$requestId = $this->session->userdata('requestId');
		$src = $this->session->userdata('phone_number');


		$this->config->load('gapit_config');
		$msgbody = $this->config->item('gapit_sendSMS');
		//$answer = $this->sendSMS($src, $requestId, $msgbody);
		// 		var_dump($answer);
		$this->load->model('User_model');

		$this->User_model->activeUser($id,$otp);
		$this->session->unset_userdata('id');
		$this->session->unset_userdata('otp');
		$this->session->unset_userdata('requestId');
		$this->session->unset_userdata('phone_number');
		$this->load->view('index');

	}
	function dob_check() {
		$day = $this->input->post('day');
		$month = $this->input->post('month');
		$year = $this->input->post('year');
		if ((is_numeric($day))&&(is_numeric($month))&&(is_numeric($year))) {
			if (checkdate($month,$day,$year)) {
				return true;
			}
		}
		$this->form_validation->set_message('dob_check', 'Bạn cần nhập %s chính xác');
		return false;

	}
	function OTPRequest($src, $requestId) {
		$this->load->library("nuSoap_lib");
		$CI =& get_instance();
		$CI->config->load('gapit_config');
		try {
			$client = new nusoap_client($CI->config->item('gapit_OTPService'),true);
		}
		catch (Exception $e) {
			// 			echo $e->getMessage(); die();
		}
		$err = $client->getError();
		if ($err) {
			// Display the error
			// 			echo "client construction error:" . $err ;
		} else {
			// 			/var_dump($client->__getFunctions());
			$answer = $client->call('OTPRequest',
					array(
							'src'=>$src, //End user mobile number
							'requestId'=>$requestId, //Unique ID from CP
							'service' =>$CI->config->item('gapit_service'), //Service key word
							'username'=>$CI->config->item('gapit_username'),
							'password'=>$CI->config->item('gapit_password')
					));

			$err = $client->getError();
			if ($err) {
				// Display the error
				// 				echo 'Call error: ' . $err;
				// 				print_r($client->response);
				// 				print_r($client->getDebug());
			} else {
				return $answer;

				//Array ( [OTPRequestResult] => 200 )
			}
		}
	}
	function SUBRequest($src, $requestId, $otp) {
		// 		src  End user mobile number  String  84914557887
		// 		requestId  Request ID correspond with OTPRequest's Id  String  1
		// 		service  Service key word  String  DK TY
		// 		otp  Otp (6 characters) is submitted by user  String  123456
		// 		username  Customer ID of Gapit  String  cp
		// 		password  Customer password of Gapit  String  cp
		$this->load->library("nuSoap_lib");
		$CI =& get_instance();
		$CI->config->load('gapit_config');
		try {
			$client = new nusoap_client($CI->config->item('gapit_OTPService'),true);
		}
		catch (Exception $e) {
			// 			echo $e->getMessage(); die();
		}
		$err = $client->getError();
		if ($err) {
			// Display the error
			// 			echo "client construction error:" . $err ;
		} else {
			// 			/var_dump($client->__getFunctions());
			$answer = $client->call('SUBRequest',
					array(
							'src'=>$src, //End user mobile number
							'requestId'=>$requestId, //Unique ID from CP
							'service' =>$CI->config->item('gapit_service'), //Service key word
							'otp'=> $otp,
							'username'=>$CI->config->item('gapit_username'),
							'password'=>$CI->config->item('gapit_password')
					));
			// 			var_dump($src);
			// 			var_dump($requestId);
			// 			var_dump($otp);
			$err = $client->getError();
			if ($err) {
				// Display the error
				// 				echo 'Call error: ' . $err;
				// 				print_r($client->response);
				// 				print_r($client->getDebug());
			} else {
				return $answer;

				//Array ( [OTPRequestResult] => 200 )
			}
		}
	}
	function sendSMS() {
		// requestId  Unique ID from CP  String  1
		// src  End user mobile number  String  84914557887
		// dest  Service number  String  8969
		// service  Service key word  String  DK TY
		// msgbody  Message content send to end user.  String  Hello world Note: message length less than 160
		// reqtime   Requested time strickly in “yyyyMMddHHmmss”
		// username  Customer ID of Gapit  String  cp
		// password  Customer password of Gapit  String  cp
		$src = $this->input->get('src');
		//requestID
		$uniqid = uniqid();
		$rand_start = rand(1,5);
		$rand_8_char = substr($uniqid,$rand_start,8);

		$this->load->library("nuSoap_lib");
		$CI =& get_instance();
		$CI->config->load('gapit_config');
		try {
			$client = new nusoap_client($CI->config->item('gapit_SendSMSService'),true);
		}
		catch (Exception $e) {
			// 			echo $e->getMessage(); die();
		}
		$err = $client->getError();
		if ($err) {
			// Display the error
			// 			echo "client construction error:" . $err ;
		} else {


			$date = new DateTime('now');
			$str_server_now = $date->format('YmdHis');
			if($this->startsWith($src, '0')) {
				$src = substr_replace($src, '84', 0-strlen($src),1);
			}
			//echo $src;
			if($this->startsWith($src, '84')) {
				$src_param = substr_replace($src, '0', 0-strlen($src),2);
			}
			$CI->load->model('User_model');
			$user = $CI->User_model->getUserByPhoneNumber($src_param);
			if (!$user) {
				return 0;
			}
			$dob_month = date("m",strtotime($user->birthday));
			$dob_date = date("d",strtotime($user->birthday));
			$map_url = 'http://123.30.187.131:8182/chiemtinh/v1/fmc/horoscope/getdaily/sign/'.$dob_date.$dob_month.'/type/1/ver/1.xml';
			if (($response_xml_data = file_get_contents($map_url))===false){
				//echo "Error fetching XML\n";
			} else {
				libxml_use_internal_errors(true);
				$data = simplexml_load_string($response_xml_data);
				if (!$data) {
					echo "Error loading XML\n";
					foreach(libxml_get_errors() as $error) {
						echo "\t", $error->message;
					}
				} else {
					if($data->response->code == 200) {
						$msgbody = $data->response->data;
					}
					if (($msgbody == null)||(strlen($msgbody) == 0)) {
						$msgbody = 'CHIEM TINH chuc ban mot ngay vui ve!';
					}
					else {
						$msgbody = $this->changeVietnamese($msgbody);
					}
				}
			}
			$msgbody = $this->getSMSMsgbody($msgbody); //160 ky tu
			$answer = $client->call('sendSMS',
					array(
							'requestId' => $rand_8_char, //   Unique ID from CP  String  1
							'src'=> $src, //End user mobile number  String  84914557887
							'dest' => '8969', //Service number  String  8969
							'service' => $CI->config->item('gapit_service'),  //Service key word  String  DK TY
							'msgbody' => $msgbody, //Message content send to end user.  String  Hello world Note: message length less than 160
							'reqtime' => $str_server_now,   //Requested time strickly in “yyyyMMddHHmmss”
							'username'=>$CI->config->item('gapit_username'),
							'password'=>$CI->config->item('gapit_password')
					));
			// 			var_dump($src);
			// 			var_dump($requestId);
			// 			var_dump($otp);
			$err = $client->getError();
			if ($err) {
				// 				shell_exec("crontab -r");
				// Display the error
				// 				echo 'Call error: ' . $err;
				// 				print_r($client->response);
				// 				print_r($client->getDebug());
				return 0;
			} else {
				// 				shell_exec("crontab -r");
				$CI->load->model('Gapit_model');

				$CI->Gapit_model->sms_log($rand_8_char, $src, $msgbody, $answer['sendSMSResult']['status']);
				return $answer;

				//Array ( [OTPRequestResult] => 200 )
			}
		}
	}
	function sendSMSWithParams($src, $msgbody) {
		// requestId  Unique ID from CP  String  1
		// src  End user mobile number  String  84914557887
		// dest  Service number  String  8969
		// service  Service key word  String  DK TY
		// msgbody  Message content send to end user.  String  Hello world Note: message length less than 160
		// reqtime   Requested time strickly in “yyyyMMddHHmmss”
		// username  Customer ID of Gapit  String  cp
		// password  Customer password of Gapit  String  cp
		// $src = $this->input->get('src');
		//requestID
		$uniqid = uniqid();
		$rand_start = rand(1,5);
		$rand_8_char = substr($uniqid,$rand_start,8);

		$this->load->library("nuSoap_lib");
		$CI =& get_instance();
		$CI->config->load('gapit_config');
		try {
			$client = new nusoap_client($CI->config->item('gapit_SendSMSService'),true);
		}
		catch (Exception $e) {
			// 			echo $e->getMessage(); die();
		}
		$err = $client->getError();
		if ($err) {
			// Display the error
			// 			echo "client construction error:" . $err ;
		} else {


			$date = new DateTime('now');
			$str_server_now = $date->format('YmdHis');
			if($this->startsWith($src, '0')) {
				$src = substr_replace($src, '84', 0-strlen($src),1);
			}
			//echo $src;
			if($this->startsWith($src, '84')) {
				$src_param = substr_replace($src, '0', 0-strlen($src),2);
			}

			$answer = $client->call('sendSMS',
					array(
							'requestId' => $rand_8_char, //   Unique ID from CP  String  1
							'src'=> $src, //End user mobile number  String  84914557887
							'dest' => '8969', //Service number  String  8969
							'service' => $CI->config->item('gapit_service'),  //Service key word  String  DK TY
							'msgbody' =>  $msgbody, //Message content send to end user.  String  Hello world Note: message length less than 160
							'reqtime' => $str_server_now,   //Requested time strickly in “yyyyMMddHHmmss”
							'username'=>$CI->config->item('gapit_username'),
							'password'=>$CI->config->item('gapit_password')
					));
			// 			var_dump($src);
			// 			var_dump($requestId);
			// 			var_dump($otp);
			$err = $client->getError();
			if ($err) {
				// Display the error
				// 				echo 'Call error: ' . $err;
				// 				print_r($client->response);
				// 				print_r($client->getDebug());
			} else {
				$CI->load->model('Gapit_model');

				$CI->Gapit_model->sms_log($rand_8_char, $src, $msgbody, $answer['sendSMSResult']['status']);
				return $answer;

				//Array ( [OTPRequestResult] => 200 )
			}
		}
	}
// 	function test() {
		
// 	}
	function startsWith($haystack, $needle)
	{
		return $needle === "" || strpos($haystack, $needle) === 0;
	}
// 	function test3() {
// 		$src_param = '01224202980';
// 		echo 2;
// 		$this->load->model("User_model");
// 		echo 1;
// 		$this->User_model->activeUserByPhoneNumber($src_param);
// 		echo 2;
// 	}
// 	function test2 () {
// 		$src = '841224202980';
// 		if($this->startsWith($src, '84')) {
// 			$src_param = substr_replace($src, '0', 0-strlen($src),2);
// 			$this->load->model("User_model");
// 			$this->User_model->deactiveUserByPhoneNumber($src_param);
// 		}
// 	}
	function changeVietnamese($q2g) {
		$ttk = array(
				'a'	=>	array('ấ','ầ','ẩ','ẫ','ậ','Ấ','Ầ','Ẩ','Ẫ','Ậ','ắ','ằ','ẳ','ẵ','ặ','Ắ','Ằ','Ẳ','Ẵ','Ặ','á','à','ả','ã','ạ','â','ă','Á','À','Ả','Ã','Ạ','Â','Ă'),
				'e' =>	array('ế','ề','ể','ễ','ệ','Ế','Ề','Ể','Ễ','Ệ','é','è','ẻ','ẽ','ẹ','ê','É','È','Ẻ','Ẽ','Ẹ','Ê'),
				'i'	=>	array('í','ì','ỉ','ĩ','ị','Í','Ì','Ỉ','Ĩ','Ị'),
				'o'	=>	array('ố','ồ','ổ','ỗ','ộ','Ố','Ồ','Ổ','Ô','Ộ','ớ','ờ','ở','ỡ','ợ','Ớ','Ờ','Ở','Ỡ','Ợ','ó','ò','ỏ','õ','ọ','ô','ơ','Ó','Ò','Ỏ','Õ','Ọ','Ô','Ơ'),
				'u'	=>	array('ứ','ừ','ử','ữ','ự','Ứ','Ừ','Ử','Ữ','Ự','ú','ù','ủ','ũ','ụ','ư','Ú','Ù','Ủ','Ũ','Ụ','Ư'),
				'y'	=>	array('ý','ỳ','ỷ','ỹ','ỵ','Ý','Ỳ','Ỷ','Ỹ','Ỵ'),
				'd'	=>	array('đ','Đ'),
		);
		foreach ($ttk as $key => $arr)
			foreach ($arr as $val)
			$q2g = str_replace($val,$key,$q2g);
		return $q2g;
	}
	function getSMSMsgbody($msgbody){
		$str = '';
		if (strlen($msgbody)<=160){
			$str = $msgbody;
		}
		else {
			$pos = strpos($msgbody,'.');
			//echo $pos;


			if ($pos < 160){
				$str = substr($msgbody, 0, $pos);
			}
			else {
				$str = substr($msgbody, 0, 160);
			}
		}
		return $str;
	}
	////////////////////////////////////////////////////////////////////////////////////////
	/***
	 * gui sms hang ngay
	* crontab hang ngay vao luc 7h sang
	*
	*/
	function sendSMSDaily() {
		$uid = $this->input->get('uid');
		$this->load->model("User_model");
		$user_array = $this->User_model->getTop2Users($uid);
		if (count($user_array) == 0) {
			echo 0;
			return 0;
		}
		foreach ($user_array as $user) {

			$dob_month = date("m",strtotime($user->birthday));
			$dob_date = date("d",strtotime($user->birthday));
			$map_url = 'http://123.30.187.131:8182/chiemtinh/v1/fmc/horoscope/getdaily/sign/'.$dob_date.$dob_month.'/type/1/ver/1.xml';
			if (($response_xml_data = file_get_contents($map_url))===false){
				//echo "Error fetching XML\n";
			} else {
				libxml_use_internal_errors(true);
				$data = simplexml_load_string($response_xml_data);
				if (!$data) {
					echo "Error loading XML\n";
					foreach(libxml_get_errors() as $error) {
						echo "\t", $error->message;
					}
				} else {
					if($data->response->code == 200) {
						$msgbody = $data->response->data;
					}
					if (($msgbody == null)||(strlen($msgbody) == 0)) {
						$msgbody = 'CHIEM TINH chuc ban mot ngay vui ve!';
					}
					else {
						$msgbody = $this->changeVietnamese($msgbody);
					}
				}
			}
			$this->sendSMSWithParams($user->phone_number,$msgbody);
		}
		$user2 = $user_array[count($user_array)-1];
		echo $user2->id;
	}
	// 	function resetSMSStatus() {
	// 		$this->load->model("User_model");
	// 		$user_array = $this->User_model->resetSMSStatus();
	// 	}
}